﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine.Events;

public class Warehouse
{
    public string name { get; set; }
    public Dictionary<int, Item> items { get { return m_Items; }set { m_Items = value; } }

    Dictionary<int, Item> m_Items = new Dictionary<int, Item>();

    public UnityEvent<int, int> onAddItem = new UnityEvent<int, int>();

    public Item GetItem(int typeID)
    {
        if(m_Items.ContainsKey(typeID))
        {
            return m_Items[typeID];
        }
        return null;
    }
    public void AddItem(Item item)
    {
        if(m_Items.ContainsKey(item.typeID))
        {
            m_Items[item.typeID].number += item.number;
        }
        else
        {
            m_Items.Add(item.typeID, item);
        }
        onAddItem.Invoke(item.typeID, item.number);
    }
    public void AddItem(int typeID, int number)
    {
        var item = ItemManager.Instance.FindItem(typeID);
        if (item == null)
            return;
        item.number = number;
        AddItem(item);
    }
    /// <summary>
    /// 移除仓库里的东西，如果number = -1则移除全部该种类
    /// </summary>
    /// <param name="item"></param>
    public void RemoveItem(Item item, int number = -1)
    {
        if(item == null)
        {
            MessageShow.Instance.Error("you are trying to remove a invaild item");
            return;
        }    
        if(m_Items.ContainsKey(item.typeID) && m_Items[item.typeID].number > item.number+1)
        {
            m_Items[item.typeID].number -= item.number;
        }
        else
        {
            m_Items.Remove(item.typeID);
        }
    }
    public void RemoveItem(int typeID, int number = -1)
    {
        if (!m_Items.ContainsKey(typeID))
        {
            MessageShow.Instance.Error("you are trying to remove a not existing item");
            return;
        }
        if (m_Items[typeID].number >= number + 1)
        {
            m_Items[typeID].number -= number;
        }
        else
        {
            m_Items.Remove(typeID);
        }
    }
}